<template>
  <div class="prodetail">
    <van-nav-bar fixed title="菜品详情页" left-arrow @click-left="$router.go(-1)" />
    <div class="dish">
      <van-swipe :autoplay="3000" @change="onChange">
        <van-swipe-item v-for="(image, index) in images" :key="index">
          <img :src="image" />
        </van-swipe-item>
        <template #indicator>
          <div class="custom-indicator">{{ current + 1 }} / {{ images.length }}</div>
        </template>
      </van-swipe>
      <div class="info">
        <div class="msg text-ellipsis-2">
          {{ DishBasicDto.dishName }}
        </div>
        <div class="title">
          <div class="price">
            <span class="now">￥{{ DishBasicDto.price * 0.5 + 0.99 }}</span>
            <span class="oldprice">￥{{ DishBasicDto.price }}</span>
          </div>
          <div class="sellcount">已售1001件</div>
        </div>
      </div>
      <hr />
      <div class="comment">
        <div class="comment-title">
          <div class="left">菜品详情：</div>
        </div>
        <div class="comment-list">
          <div class="comment-list-item">
            <van-row>
              <van-col span="8">菜品描述：</van-col>
              <van-col span="16" style="font-size: 14px;color: #000;">
                {{ DishBasicDto.description }}
              </van-col>
            </van-row>
          </div>
          <div class="comment-list-item" v-if="flavorList.length > 0">
            <van-row>
              <van-col span="8">可选口味：</van-col>
              <van-col span="16" style="font-size: 14px;color: #000;">
                <div v-for="(item, index) in flavorList" :key="index">
                  <p>{{ item.flavorName }}：</p>
                  <p>{{ item.flavorList }}</p>
                </div>
              </van-col>
            </van-row>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部 -->
    <div class="footer">
      <van-goods-action>
        <van-goods-action-icon icon="wap-home-o" text="首页" @click="$router.go(-1)"/>
        <van-goods-action-icon icon="chat-o" text="客服"/>
        <van-goods-action-icon icon="cart-o" text="购物车" :badge="cartTotal" @click="$router.push('/cart')"/>
        <!-- <van-stepper v-model="cartItem.num" theme="round" input-width="100px" button-size="32px" disable-input v-if="cartItem.num > 0" min="0"/> -->
        <van-goods-action-button type="danger" text="加入购物车" v-if="flavorList.length > 0" @click="selectFlavor"/>
        <van-goods-action-button type="danger" text="加入购物车" v-else @click="addCart"/>
      </van-goods-action>
    </div>
    <!-- 口味选择弹窗 -->
    <van-dialog v-model="show" title="口味选择" show-cancel-button @confirm="addCart">
      <div class="content">
        <ul>
          <li v-for="(dishFlavor, index) in dishFlavorList" :key="index" class="item">
            <p class="item-p">{{ dishFlavor.flavorName }}</p>
            <div class="item-tags">
              <van-tag plain type="warning" size="large" v-for="(fl, ind) in dishFlavor.flavorList" :key="ind"
                @click="getFlavorTag">
                {{ fl }}
              </van-tag>
            </div>
          </li>
        </ul>
      </div>
    </van-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import store from '@/store'
import request from '@/utils/request'
import { mapGetters } from 'vuex'
import { Toast } from 'vant'

export default {
  name: 'DishDetail',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
  // 这里存放数据
    return {
      baseCart: '/shopping-cart',
      DishBasicDto: {},
      images: ['https://img01.yzcdn.cn/vant/cat.jpeg'],
      flavorList: [],
      current: 0,
      cartItem: {
        id: 0,
        dishId: 0,
        setmeal: 0,
        num: 0,
        flavorString: '',
        totalMoney: 0
      },
      show: false,
      dishFlavorList: [],
      plain: true,
      flavorNameList: []
    }
  },
  // 监听属性 类似于data概念
  computed: {
    ...mapGetters('cart', ['cartTotal'])
  },
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    onChange (index) {
      this.current = index
    },
    getImages (imagesUrl) {
      if (imagesUrl !== '') {
        this.images = imagesUrl.split(',')
      }
    },
    getFlavorList (dishFlavors) {
      if (dishFlavors !== null) {
        dishFlavors.forEach(item => {
          const dishFlavor = {
            flavorName: '',
            flavorList: ''
          }
          dishFlavor.flavorName = item.flavorName
          JSON.parse(item.flavorList).forEach(item => {
            dishFlavor.flavorList += item.name + '，'
          })
          dishFlavor.flavorList = dishFlavor.flavorList.slice(0, -1)
          this.flavorList.push(dishFlavor)
        })
      }
    },
    // 选择口味
    selectFlavor () {
      this.show = true
      const temp = []
      this.DishBasicDto.dishFlavors.forEach(item => {
        const dishFlavor = {
          flavorName: '',
          flavorList: []
        }
        dishFlavor.flavorName = item.flavorName
        JSON.parse(item.flavorList).forEach(i => {
          dishFlavor.flavorList.push(i.name)
        })
        temp.push(dishFlavor)
      })
      this.dishFlavorList = temp
    },
    // 点击的口味标签互斥
    getFlavorTag (e) {
      const flavorLists = []
      this.dishFlavorList.forEach(item => {
        flavorLists.push(...item.flavorList)
      })
      let firstSpan = ''
      let length = 0
      this.dishFlavorList.forEach(dishFlavor => {
        if (dishFlavor.flavorList.indexOf(e.srcElement.innerText) !== -1) {
          firstSpan = dishFlavor.flavorList[0]
          length = dishFlavor.flavorList.length
        }
      })
      const index = flavorLists.indexOf(firstSpan)
      Array.from(document.querySelectorAll('.item-tags .van-tag')).slice(index, index + length).forEach(tag => {
        if (e.srcElement.innerText === tag.innerText) {
          e.target.classList.remove('van-tag--plain')
        } else {
          let flavorList = []
          this.dishFlavorList.forEach(dish => {
            if (dish.flavorName === '忌口') {
              flavorList = dish.flavorList
            }
          })
          if (flavorList.indexOf(e.srcElement.innerText) === -1) {
            tag.classList.add('van-tag--plain')
          }
        }
      })
    },
    // 加入购物车
    addCart () {
      document.querySelectorAll('.item-tags .van-tag').forEach(tag => {
        if (!tag.classList.contains('van-tag--plain')) {
          this.flavorNameList.push(tag.innerText)
        }
      })
      document.querySelectorAll('.item-tags .van-tag').forEach(tag => {
        tag.classList.add('van-tag--plain')
      })
      this.cartItem.dishId = this.DishBasicDto.id
      this.flavorNameList = [...new Set(this.flavorNameList)]
      this.cartItem.flavorString = JSON.stringify(this.flavorNameList)
      this.cartItem.num = 1
      this.cartItem.totalMoney = this.DishBasicDto.price * 0.5 + 0.99
      // console.log(this.cartItem)
      // 判断当前用户是否登录（即有无token）
      const token = store.state.user.userInfo.accessToken
      if (!token) {
        this.$dialog.confirm({
          title: '温馨提示',
          message: '此时需要先登录才能继续操作哦',
          confirmButtonText: '去登录',
          cancelButtonText: '再逛逛'
        }).then(() => {
          this.$router.replace({
            path: '/login',
            query: {
              backUrl: '/'
            }
          })
        }).catch(() => {
          this.cartItem.num = 0
        })
      } else {
        // 执行加入购物车操作
        Toast.success('加入成功')
        request({
          url: this.baseCart + '/shopping-cart',
          method: 'post',
          data: this.cartItem
        }).then(() => {
          this.$store.dispatch('cart/getCartAction')
        })
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.DishBasicDto = this.$route.params.dishBasicDto
    this.getImages(this.DishBasicDto.image)
    this.getFlavorList(this.DishBasicDto.dishFlavors)
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="less" scoped>
.van-dialog {
  padding: 0 auto;

  .content {
    margin-left: 20px;
    margin-bottom: 20px;

    .item {
      margin-top: 15px;

      .item-tags {
        margin-top: 9px;

        .van-tag {
          margin-right: 8px;
          margin-top: 5px;
        }
      }
    }
  }
}
.prodetail {
  padding-top: 46px;
  background-color: #f7f7f7;
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }

  .dish {
    background-color: #fff;
    margin: 6px auto;
    width: 97%;
    border-radius: 10px;
    height: 600px;
    padding: 10px;
  }
  img {
    display: block;
    width: 100%;
  }
  .custom-indicator {
    position: absolute;
    right: 10px;
    bottom: 10px;
    padding: 5px 10px;
    font-size: 12px;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 15px;
  }
  .desc {
    width: 100%;
    overflow: scroll;
    ::v-deep img {
      display: block;
      width: 100%!important;
    }
  }
  .info {
    padding: 10px;
  }
  .title {
    display: flex;
    justify-content: space-between;
    .now {
      color: #fa2209;
      font-size: 20px;
    }
    .oldprice {
      color: #959595;
      font-size: 16px;
      text-decoration: line-through;
      margin-left: 5px;
    }
    .sellcount {
      color: #959595;
      font-size: 16px;
      position: relative;
      top: 4px;
    }
  }
  .msg {
    font-size: 18px;
    line-height: 24px;
    font-weight: 600;
    margin-top: 5px;
  }
  .service {
    display: flex;
    justify-content: space-between;
    line-height: 40px;
    margin-top: 10px;
    font-size: 16px;
    background-color: #fafafa;
    .left-words {
      span {
        margin-right: 10px;
      }
      .van-icon {
        margin-right: 4px;
        color: #fa2209;
      }
    }
  }

  .comment {
    padding: 10px;
  }
  .comment-title {
    display: flex;
    justify-content: space-between;
    .left {
      font-size: 16px;
    }
  }

  .comment-list {
    margin-top: 15px;
    font-size: 16px;
    color: #959595;

    .comment-list-item {
      width: 100%;
      margin-bottom: 10px;
      height: 50px;
    }
  }

  .comment-item {
    font-size: 16px;
    line-height: 30px;
    .top {
      height: 30px;
      display: flex;
      align-items: center;
      margin-top: 20px;
      img {
        width: 20px;
        height: 20px;
      }
      .name {
        margin: 0 10px;
      }
    }
    .time {
      color: #999;
    }
  }
}
.tips {
  padding: 10px;
}
.footer {
  .van-stepper {
    margin-left: 30px;
  }
}
</style>
